package com.system.Controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.common.Constant.Constants;
import com.common.Entity.Result;
import com.system.Service.VerificationCodeService;
import com.common.Utils.JwtUtil;
import com.github.pagehelper.PageInfo;
import com.system.Entity.*;
import com.system.Mapper.UserMapper;
import com.system.Service.UserService;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VerificationCodeService verificationCodeService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @PostMapping("/login/account")
    public Result<String> Accountlogin(@RequestBody LoginContext loginContext) {
        String token = userService.Accountlogin(loginContext);
        if (token.equals("false")) {
            return Result.error(Constants.LOGIN_ERROR);
        } else if (token.equals("pwdError")) {
            return Result.error(Constants.USERNAME_PASSWORD_ERROR);
        } else if (token.equals("UserError_D")) {
            return Result.error(Constants.USER_STATUS_DISABLE_ERROR);
        } else if (token.equals("UserError_N")) {
            return Result.error(Constants.USERNAME_PASSWORD_ERROR);
        }

        return Result.success(token); // 返回token
    }


    @PostMapping("/login/phone")
    public Result<String> Phonelogin(@RequestBody LoginContext loginContext) {
        String phone = loginContext.getPhone();
        int result = userMapper.funPhone(phone);
        if (result == 0) {
            return Result.error("手机号未注册!");
        }
        String code = loginContext.getCode();
        String token;
        if (code == null) {
            return Result.error("验证码不能为空");
        } else {
            boolean BackResult = verificationCodeService.verifyCode("phone", phone, code);
            if (BackResult) {
                token = userService.Phonelogin(loginContext);
                if (token.equals("false")) {
                    return Result.error(Constants.LOGIN_ERROR);
                } else if (token.equals("UserError_D")) {
                    return Result.error(Constants.USER_STATUS_DISABLE_ERROR);
                }
            } else {
                return Result.error("验证码错误!");
            }
        }
        return Result.success(token); // 返回token
    }

    @PostMapping("/login/email")
    public Result<String> Emaillogin(@RequestBody LoginContext loginContext) {
        String email = loginContext.getEmail();
        int result = userMapper.funEmail(email);
        if (result == 0) {
            return Result.error("邮箱未注册!");
        }
        String code = loginContext.getCode();
        String token;
        if (code == null) {
            return Result.error("验证码不能为空");
        } else {
            boolean BackResult = verificationCodeService.verifyCode("email", email, code);
            if (BackResult) {
                token = userService.Emaillogin(loginContext);
                if (token.equals("false")) {
                    return Result.error(Constants.LOGIN_ERROR);
                } else if (token.equals("UserError_D")) {
                    return Result.error(Constants.USER_STATUS_DISABLE_ERROR);
                }
            } else {
                return Result.error("验证码错误!");
            }
        }
        return Result.success(token); // 返回token
    }


    @PostMapping("/register")
    public Result register(@RequestBody Register registry) throws ParseException {

        //验证验证码是否正确
        String code = registry.getPhoneCode();
        String phone = registry.getPhone();

        if (code == null) {
            return Result.error("验证码不能为空");
        } else {
            Boolean BackResult = verificationCodeService.verifyCode("phone", phone, code);
            if (BackResult) {
                String result = userService.register(registry);
                if (result.equals("ok")) {
                    return Result.success();
                } else if (result.equals("User_Have")) {
                    return Result.error(Constants.USERNAME_EXIST);
                } else if (result.equals("Email_Have")) {
                    return Result.error(Constants.EMAIL_EXIST);
                } else if (result.equals("Phone_Have")) {
                    return Result.error(Constants.PHONE_EXIST);
                }
            } else {
                return Result.error("验证码错误!");
            }
        }
        return Result.success();
    }


    //获取个人信息 验证token有效性
    @GetMapping("/profile")
    public Result<User> getUserProfile(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            String username = JwtUtil.extractUsername(token);
            //校验token有效性
            boolean isValid = JwtUtil.validateToken(token, username);
            if (!isValid) {
                return Result.error(Constants.LOGIN_ERROR);
            } else {
                String redistoken = redisTemplate.opsForValue().get(username);
                if (redistoken == null) {
                    return Result.error(Constants.LOGIN_ERROR);
                } else {
                    User user = userMapper.SerachUsername(username);
                    int roleId = userMapper.getRole(user.getUserId());
                    user.setRoleId(roleId);
                    return Result.success(user);
                }
            }
        }
        return Result.error(Constants.LOGIN_ERROR);
    }


    //重新生成token
    // 重新生成 token
//    @GetMapping("/validateToken")
//    public Result<String> validateToken(@RequestParam String token) {
////        // 检查 token 是否过期
////        if (JwtUtil.isTokenExpired(token)) {
////            // 验证 token 的有效性
////            if (JwtUtil.validateToken(token, JwtUtil.extractUsername(token))) {
////                String username = JwtUtil.extractUsername(token);
////                String redistoken = redisTemplate.opsForValue().get(username);
////                // 检查 Redis 中是否存在 token
////                if (redistoken == null) {
////                    return Result.error(Constants.TOKEN_EXPIRED);
////                } else {
////                    // 重新生成 token
////                    String newToken = JwtUtil.generateToken(username);
////
////                    redisTemplate.delete(username);
////                    // 更新 Redis 中的 token 有效时间
////                    redisTemplate.opsForValue().set(username, newToken, 3600, TimeUnit.SECONDS);
////                    return Result.success(newToken); // 返回新的 token
////                }
////            } else {
////                return Result.error(Constants.LOGIN_ERROR);
////            }
////        } else {
////            return Result.error(Constants.TOKEN_EXPIRED);
////        }
//        // 检查 token 是否过期
//
//            // 验证 token 的有效性
////            if (JwtUtil.validateToken(token, JwtUtil.extractUsername(token))) {
//            if (JwtUtil.isTokenExpired(token)) {
//            throw new RuntimeException("Token 已过期");
//            }
//            String username = JwtUtil.extractUsername(token);
//            String redistoken = redisTemplate.opsForValue().get(username);
//            // 检查 Redis 中是否存在 token
//            if (redistoken == null) {
//                return Result.error(Constants.TOKEN_EXPIRED);
//            } else {
//                // 重新生成 token
//                String newToken = JwtUtil.generateToken(username);
//
//                redisTemplate.delete(username);
//                // 更新 Redis 中的 token 有效时间
//                redisTemplate.opsForValue().set(username, newToken, 3600, TimeUnit.SECONDS);
//                return Result.success(newToken); // 返回新的 token
//            }
//
////            } else {
////                return Result.error(Constants.LOGIN_ERROR);
////            }
//    }



    @GetMapping("/validateToken")
    public Result<String> validateToken(@RequestParam String token) {
        try {
            if (JwtUtil.isTokenExpired(token)) {
                throw new RuntimeException("Token 已过期");
            }
            String username = JwtUtil.extractUsername(token);
            String redisToken = redisTemplate.opsForValue().get(username);

            if (redisToken == null || !redisToken.equals(token)) {
                return Result.error(Constants.TOKEN_EXPIRED);
            }

            // 重新生成 token
            String newToken = JwtUtil.generateToken(username);

            // 更新 Redis 中的 token
            redisTemplate.delete(username);
            redisTemplate.opsForValue().set(username, newToken, 3600, TimeUnit.SECONDS);

            return Result.success(newToken);
        } catch (Exception e) {
            return Result.error(Constants.LOGIN_ERROR);
        }
    }
    @PutMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam("avatar") MultipartFile avatar,
                               @RequestParam("token") String token) {
        try {
            // 从token中解析用户名
            String username = JwtUtil.extractUsername(token);

            if (username == null) {
                return Result.error("无效的token");
            }

            // 获取文件名
            String originalFilename = avatar.getOriginalFilename();
            //取文件后缀
            String suffix = null;
            if (originalFilename != null) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String newFileName = UUID.randomUUID().toString() + suffix;
            String objectName = "UserAvatar/" + newFileName;

            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            String urlPrefix = "https://" + bucketName + "." + endpoint;

            try (InputStream inputStream = avatar.getInputStream()) {
                // 上传文件到OSS
                ossClient.putObject(bucketName, objectName, inputStream);

                // 获取头像URL
                String avatarUrl = urlPrefix + "/" + objectName;

                // 更新用户头像URL到数据库
                userService.updateUserAvatar(username, avatarUrl);

                return Result.success("头像更新成功", avatarUrl);
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        } catch (IOException e) {
            return Result.error("文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            return Result.error("头像更新失败：" + e.getMessage());
        }
    }

    @PutMapping("/updateProfile")
    public Result updateProfile(@RequestBody User user) throws ParseException {

        userService.updateUserProfile(user);

        return Result.success();
    }

    @PutMapping("/updatePhone")
    public Result updatePhone(@RequestBody ChangeCommon changeCommon) {
        String phone = changeCommon.getPhone();
        String code = changeCommon.getCode();
        String token = changeCommon.getToken();
        String username = JwtUtil.extractUsername(token);
        if (verificationCodeService.verifyCode("phone", phone, code)) {
            userMapper.updatePhoneByUserName(username, phone);
            return Result.success();
        } else {
            return Result.error("验证码错误!");
        }
    }

    @PostMapping("/updateEmail")
    public Result updateEmail(@RequestBody ChangeCommon changeCommon) {
        String email = changeCommon.getEmail();
        String code = changeCommon.getCode();
        String token = changeCommon.getToken();
        String username = JwtUtil.extractUsername(token);
        if (verificationCodeService.verifyCode("email", email, code)) {
            userMapper.updateEmailByUserName(username, email);
            return Result.success();
        } else {
            return Result.error("验证码错误!");
        }
    }

    @PutMapping("/changePassword")
    public Result changePassword(@RequestBody ChangeCommon changeCommon) {
        String username = JwtUtil.extractUsername(changeCommon.getToken());
        if (userService.changePassword(username, changeCommon.getOldPWD(), changeCommon.getNewPWD())) {
            return Result.success();
        } else {
            return Result.error("旧密码错误!");
        }
    }

    @PutMapping("/resetpwdByphone")
    public Result resetpwdByphone(@RequestBody ChangeCommon changeCommon) {
        String phone = changeCommon.getPhone();
        String code = changeCommon.getCode();
        String newPWD = changeCommon.getNewPWD();
        User user = userMapper.SerachPhone(phone);
        if (user == null) {
            return Result.error("手机号未注册!");
        } else {
            if (user.getStatus().equals(Constants.USER_STATUS_DISABLE)) {
                return Result.error("用户已被禁用!");
            }
            if (user.getStatus().equals(Constants.USER_STATUS_FREEZE)) {
                return Result.error("用户已被冻结!");
            }
            if (verificationCodeService.verifyCode("phone", phone, code)) {
                userService.changePassword_Login(user.getUserName(), newPWD);
                return Result.success();
            }
        }
        return Result.error("系统错误!");
    }

    @PutMapping("/resetpwdByemail")
    public Result resetpwdByemail(@RequestBody ChangeCommon changeCommon) {
        String email = changeCommon.getEmail();
        String code = changeCommon.getCode();
        String newPWD = changeCommon.getNewPWD();
        User user = userMapper.SerachEmail(email);
        if (user == null) {
            return Result.error("邮箱未注册!");
        } else {
            if (user.getStatus().equals(Constants.USER_STATUS_DISABLE)) {
                return Result.error("用户已被禁用!");
            }
            if (user.getStatus().equals(Constants.USER_STATUS_FREEZE)) {
                return Result.error("用户已被冻结!");
            }
            if (verificationCodeService.verifyCode("email", email, code)) {
                userService.changePassword_Login(user.getUserName(), newPWD);
                return Result.success();
            }
        }
        return Result.error("系统错误!");
    }

    @GetMapping("/getUserList")
    public Result getUserList(@RequestParam Integer pageNum,
                              @RequestParam Integer pageSize,
                              @RequestParam(required = false) String userName) {
        PageInfo<User> pageInfo = userService.getUserList(pageNum, pageSize, userName);
        return Result.success(pageInfo);
    }

    @GetMapping("/getRoleList")
    public Result getRoleList(@RequestParam Integer pageNum,
                              @RequestParam Integer pageSize) {
        PageInfo<Role> pageInfo = userService.getRoleList(pageNum, pageSize);
        return Result.success(pageInfo);
    }

    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody User user) {
        String userId = user.getUserId();
        Integer status = user.getStatus();
        userMapper.updateStatusByUserId(userId, status);
        return Result.success();
    }

    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user) throws ParseException {
        String result = userService.addUser(user);
        switch (result) {
            case "User_Have":
                return Result.error("用户已存在");
            case "ok":
                return Result.success();
        }
        return Result.error("系统错误");
    }


    //管理员修改用户角色/状态
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody User user) {
        String token= user.getToken();
        String username = JwtUtil.extractUsername(token);
        user.setUpdateUser(username);
        userService.updateUser_A(user);

        return Result.success();
    }

    @DeleteMapping("/deleteUser/{userId}")
    public Result deleteUser(@PathVariable("userId") String userId) {
        userMapper.deleteUser(userId);
        //删除用户-角色关联数据
        userMapper.deleteUser_role(userId);
        return Result.success();
    }

    @GetMapping("/getUserByName")
    public String getUserByName(@RequestParam String username) {
        User user = userService.getUserByName(username);
        return user.getUserId();
    }

    @GetMapping("/getCurrentUser/{token}")
    public Result getCurrentUser(@PathVariable("token") String token) {
        String username = JwtUtil.extractUsername(token);
        User user = userMapper.SerachUsername(username);
        return Result.success(user);
    }



}

